home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8133 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: news.tamu.edu!tpradeep
  2. From: tpradeep@cs.tamu.edu (Pradeep K Tapadiya)
  3. Newsgroups: comp.lang.c++
  4. Subject: Exceptions and operator new. Help
  5. Date: 15 Feb 1996 01:09:30 GMT
  6. Organization: Texas A&M Computer Science Department, College Station, TX
  7. Message-ID: <4fu14a$2vg@news.tamu.edu>
  8. NNTP-Posting-Host: ftcl06.cs.tamu.edu
  9.  
  10. According to the C++ specs, a new will throw a xalloc exception
  11. if memory allocation fails. The return value from new need not be
  12. NULL. In addition, the constructor can throw a different exception
  13. as defined by you, the programmer. This means, each time, I do a
  14. new, I have to do something like 
  15.  
  16.    myObject* p = NULL;
  17.  
  18.    try {
  19.      myObject* p = new myObject;
  20.    }
  21.    catch (xlloc e) {
  22.      // do not delete p here since it was never allocated
  23.      ...
  24.    }
  25.    catch (myException& e) {
  26.       delete p;
  27.     ...
  28.  
  29.  
  30. Moreover, if myObject's destructor has to do some
  31. memroy cleanup, for example,
  32.  
  33. myObject::~myObject ()
  34. {
  35.    delete [] m_pVarList;
  36. }
  37.  
  38. then, the constructor will probably has to do something like
  39.  
  40.  
  41. myObject::myObject ()
  42. {
  43.    try {
  44.      m_pVarList = new char [10];
  45.    }
  46.    catch (xalloc e) {
  47.      m_pVarList = NULL; // explicitly set it to NULL as destructor will
  48.                         // try to delete a bogus pointer
  49.      throw xalloc ();
  50.    }
  51. }
  52.  
  53. Now, setnewHandler adds another variable to the model. As you cannot
  54. rely on what third party library is doing, anytime you do a new on
  55. your object, you will explictly have to do a setnewhandler to your handler.
  56.  
  57. Though we have been programming in C++ for quite some time, this is
  58. the first time our company is venturing out into the world of
  59. exceptions. It now appears exceptions would make the development process
  60. more complicated.
  61.  
  62. Am I missing something in the way I am using exceptions?
  63. Am I abusing exception handling mechanism?
  64. How are you handling exceptions with new opeartor?
  65. How are you integrating your code with third party library/dll?
  66.  
  67. Thank you for enlightening me.
  68.  
  69. Pradeep
  70.      
  71.